const asyncHandler = require("../utils/asyncHandler");
const Comment = require("../models/Comment");
const Post = require("../models/Post");
const { success, error } = require("../utils/response");

// 获取文章的评论列表
exports.listComments = asyncHandler(async (req, res) => {
    const { postId } = req.params;
    const comments = await Comment.find({ post: postId })
        .populate("author", "username avatarUrl")
        .sort({ createdAt: -1 });
    return success(res, { items: comments })
});

// 发表（需登录）
exports.createComment = asyncHandler(async (req, res) => {
    const { postId } = req.params;
    const { content } = req.body;

    const post = await Post.findById(postId);
    if (!post)
        return error(res, '文章不存在')

    if (!post.published)
        return error(res, '不可对未发布文章评论')

    const comment = await Comment.create({
        post: postId,
        author: req.user._id,
        content,
    });

    return success(res, comment, '评论成功')
});

// 删除（作者或管理员）
exports.deleteComment = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const comment = await Comment.findById(id);
    if (!comment) 
         return error(res, '评论不存在')

    const isOwner = String(comment.author) === String(req.user._id);
    const isAdmin = req.user.role === "admin";
    if (!isOwner && !isAdmin) 
         return error(res, '无权限删除')

    await comment.deleteOne();
    return success(res, null, '已删除')
});
